package com.zgroup.services

import com.zgroup.common.CheckUtils
import com.zgroup.common.WebUtils
import com.zgroup.domain.*

class EstateService extends DynamicService {

  boolean transactional = true
  // 空档竞标

  def paginateList(params) {
    if (!params.max) {
      params.max = 10
    }
    if (!params.offset) {
      params.offset = 0
    }

    StringBuffer query = new StringBuffer()
    Collection positionalParams = []

    query.append("from Estate as e where e.approveFlag='1' and showFlag='1' ")
    String item = params.type
    if (!CheckUtils.isEmpty(item)) {
      query.append("and type = ? ")
      positionalParams.add(item)
    }
    item = params.area
    if (!CheckUtils.isEmpty(item)) {
      query.append("and area like ? ")
      positionalParams.add(item)
    }
    item = params.sector
    if (!CheckUtils.isEmpty(item)) {
      query.append("and sector = ? ")
      positionalParams.add(item)
    }
    item = params.address
    if (!CheckUtils.isEmpty(item)) {
      query.append("and address like ? ")
      positionalParams.add("%" + item + "%")
    }
    item = params.name
    if (!CheckUtils.isEmpty(item)) {
      query.append("and name like ? ")
      positionalParams.add("%" + item + "%")
    }
    return paginateList(query.toString(), positionalParams, [max: params.max, offset: params.offset, sort: params.sort, order: params.order], Estate)
  }

  /*
   * 图片入库
  */

  def storage(id, estateId, infoId) {
    def pic = Picture.get(id)
    def estate = Estate.get(estateId)

    //如果是楼盘图片，处理图片数量
    if (pic.type.equals(Picture.ESTATE_TYPE)) {
      estate.estPicNum = estate.estPicNum == null || estate.estPicNum <= 0 ? 0 : estate.estPicNum - 1;
      estate.estAcceptPicNum = estate.estAcceptPicNum == null ? 1 : estate.estPicNum + 1;
    } else if (pic.type.equals(Picture.LAYOUT_TYPE)) {
      estate.layoutPicNum = estate.layoutPicNum == null || estate.layoutPicNum <= 0 ? 0 : estate.layoutPicNum - 1;
      estate.layoutAcceptPicNum = estate.layoutAcceptPicNum == null ? 1 : estate.layoutAcceptPicNum + 1;
    }
    estate.save()

    pic.fromEstate = estate
    def publisher = InfoRelease.get(infoId).publisher
    publisher.addPhotoPresented()
    return pic.save()
  }

  def estatePic(pEstate) {

    String query = "from InfoRelease as i where ? in elements(i.estates)"
    return paginateList(query, [pEstate], [sort: "lastUpdated", order: "desc"], InfoRelease)
  }

  // 空档竞标

  def blankList(pUser, pSize, pOffset) {
    return blankList(pUser, pSize, pOffset, true)
  }

  def blankList(pUser, pSize, pOffset, isPaginate) {
    String query = "from Estate as e where e.approveFlag='1' and e.showFlag='1' and e.vipBid is null and e.firstBid is null and e.sector in (?,?)"
    if (isPaginate) {
      return paginateList(query, [pUser.homeEstate?.sector, pUser.companyEstate?.sector], [max: pSize, offset: pOffset, sort: "name"], Estate)
    }
    return [
            "items": Estate.findAll(query + makeOrderBy("e", [sort: "name"]), [pUser.homeEstate?.sector, pUser.companyEstate?.sector], [max: pSize, offset: pOffset]),
            "count": 0
    ]
  }

  // 走俏竞标

  def hotBidEstate(pDate) {
    String query = "from EstateStatistics as e where statisticsDate = ? group by e.estate order by e.totalCount desc"
    EstateStatistics.find(query, [pDate])
    //EstateStatistics.list(max:1, sort:"totalCount", order:"desc")?.getAt(0)
  }

  def biddingEstate(pEstate, pUser, pMoney, pType, pPayment) {
//        def oldBid=Bid.findByStatusAndExpiredAndEstateAndUser("20","0",pEstate,pUser)
//        if(oldBid){
//            oldBid.expired="1"
//            oldBid.save();
//        }
    Bid.executeUpdate("update Bid as b set b.expired='1' where b.expired='0' and b.status='20' and b.estate=? and b.user=? ", [pEstate, pUser])
    if ("10" == pType) {
      bidEstate(pEstate, pUser, pMoney, pPayment)
    } else if ("20" == pType) {
      vipEstate(pEstate, pUser, pMoney, pPayment)
    }
  }

  def bidEstate(pEstate, pUser, pMoney, pPayment) {
    def bid = new Bid()
    bid.estate = pEstate
    bid.user = pUser
    bid.money = pMoney
    bid.payment = pPayment
    bid.dayCost = pMoney
    if (bid.save()) {
      if (pEstate.thirdBid != null) {
        thawyBid(pEstate.thirdBid, pEstate.thirdBid.money, "20")
      }
      freezeBid(bid, bid.money)
      if (pUser == pEstate.secondBid?.user) {
        thawyBid(pEstate.secondBid, pEstate.secondBid.money, "20")
        pEstate.thirdBid = null
      } else {
        pEstate.thirdBid = pEstate.secondBid
      }

      pEstate.secondBid = pEstate.firstBid
      pEstate.firstBid = bid
      if (!pEstate.save()) {
        pEstate.errors.each {
          println it
        }
      }
      increaseBidCount(bid)
    }
  }

  def cancelBid(pBid) {
    if (pBid != null) {
      def pEstate = pBid.estate
      if (pEstate.firstBid == pBid) {
        pEstate.firstBid = pEstate.secondBid
        pEstate.secondBid = pEstate.thirdBid
        pEstate.thirdBid = null
      } else if (pEstate.secondBid == pBid) {
        pEstate.secondBid = pEstate.thirdBid
        pEstate.thirdBid = null
      } else if (pEstate.thirdBid == pBid) {
        pEstate.thirdBid = null
      } else if (pEstate.vipBid == pBid) {
        pEstate.vipBid = null
      } else {
        return true
      }
      if (!pEstate.save()) {
        pEstate.errors.each {
          println it
        }
      }
      thawyBid(pBid, pBid.money, "30")
      decreaseBidCount(pBid)
      return true
    }
  }

  def vipEstate(pEstate, pUser, pMoney, pPayment) {
    def setting = Setting.get(1)
    def bid = new Bid()
    int scale = ("30" == pPayment ? 2 : 0)
    int daysOfMonth = WebUtils.getDaysOfMonth(new Date())
    bid.estate = pEstate
    bid.type = "20"
    bid.user = pUser
    bid.money = pMoney
    bid.payment = pPayment
    bid.dayCost = pMoney.divide(daysOfMonth, scale, BigDecimal.ROUND_HALF_UP)
    if (bid.save()) {
      if (pEstate.vipBid != null) {
        thawyBid(pEstate.vipBid, pMoney, "20")
      }
      if (pUser == pEstate.firstBid?.user) {
        thawyBid(pEstate.firstBid, pEstate.firstBid.money, "30")
        pEstate.firstBid = pEstate.secondBid
        pEstate.secondBid = pEstate.thirdBid
        pEstate.thirdBid = null
      } else if (pUser == pEstate.secondBid?.user) {
        thawyBid(pEstate.secondBid, pEstate.secondBid.money, "30")
        pEstate.secondBid = pEstate.thirdBid
        pEstate.thirdBid = null
      } else if (pUser == pEstate.thirdBid?.user) {
        thawyBid(pEstate.thirdBid, pEstate.thirdBid.money, "30")
        pEstate.thirdBid = null
      }
      freezeBid(bid, pMoney)
      pEstate.vipBid = bid
      if (!pEstate.save()) {
        pEstate.errors.each {
          println it
        }
      }
      increaseBidCount(bid)
    } else {
      bid.errors.each {
        println it
      }
    }
  }

  // 竞标解冻，返还竞标金额

  def thawyBid(pBid, pCost, pStatus) {
    // 冠亚季军被挤不扣费时长(单位：小时)
    if ("20" == pStatus && pBid.isFree) {
      def user = pBid.user
      def payment = pBid.payment
      if ("10" == payment) {
        user.availablePoint += pCost
        user.freezingPoint -= pCost
      } else if ("20" == payment) {
        user.availableCoupon += pCost
        user.freezingCoupon -= pCost
      } else {
        user.availableMoney += pCost
        user.freezingMoney -= pCost
      }

      if (!user.save()) {
        user.errors.each {
          println it
        }
      }
    }
    if ("20" == pStatus) {
      Bid.executeUpdate("update Bid as b set b.expired='1' where b.expired='0' and b.status='20' and b.estate=? and b.user=? ", [pBid.estate, pBid.user])
    }
    pBid.status = pStatus
    pBid.dateCancelled = new Date()
    pBid.save()
  }

  def freezeBid(pBid, pCost) {
    def user = pBid.user
    def payment = pBid.payment
    if ("10" == payment) {
      user.availablePoint -= pCost
      user.freezingPoint += pCost
    } else if ("20" == payment) {
      user.availableCoupon -= pCost
      user.freezingCoupon += pCost
    } else {
      user.availableMoney -= pCost
      user.freezingMoney += pCost
    }

    user.save()
  }

  def increaseBidCount(pBid, pStatistics, pStatisticsDate) {
    if (pStatistics == null) {
      pStatistics = new EstateStatistics()
      pStatistics.statisticsDate = pStatisticsDate
      pStatistics.estate = pBid.estate
      if (pBid.isVipType) {
        pStatistics.vipCount = 1
      } else {
        pStatistics.bidCount = 1
      }
      pStatistics.totalCount = 1
      if (!pStatistics.save()) {
        pStatistics.errors.each {
          println it
        }
      }
    } else {
      if (pBid.isVipType) {
        pStatistics.vipCount++
      } else {
        pStatistics.bidCount++
      }
      pStatistics.totalCount++
      if (!pStatistics.save()) {
        pStatistics.errors.each {
          println it
        }
      }
    }
  }

  def increaseBidCount(pBid) {
    //每日统计
    String statisticsDate = WebUtils.formatTime(pBid.dateCreated, "yyyyMMdd")
    def statistics = EstateStatistics.findByStatisticsDateAndEstate(statisticsDate, pBid.estate)
    increaseBidCount(pBid, statistics, statisticsDate)
    //每月统计
    String statisticsYM = statisticsDate.substring(0, 6)
    statistics = EstateStatistics.findByStatisticsDateAndEstate(statisticsYM, pBid.estate)
    increaseBidCount(pBid, statistics, statisticsYM)
  }

  def decreaseBidCount(pBid, pStatistics) {
    if (pStatistics != null) {
      if (pBid.isVipType) {
        pStatistics.vipCount--
      } else {
        pStatistics.bidCount--
      }
      pStatistics.totalCount--
      if (!pStatistics.save()) {
        pStatistics.errors.each {
          println it
        }
      }
    }
  }

  def decreaseBidCount(pBid) {
    //每日统计
    String statisticsDate = WebUtils.formatTime(pBid.dateCreated, "yyyyMMdd")
    def statistics = EstateStatistics.findByStatisticsDateAndEstate(statisticsDate, pBid.estate)
    decreaseBidCount(pBid, statistics)
    //每月统计
    String statisticsYM = statisticsDate.substring(0, 6)
    statistics = EstateStatistics.findByStatisticsDateAndEstate(statisticsYM, pBid.estate)
    decreaseBidCount(pBid, statistics)
  }

  def approve(pEstateId, pFlag, pApproveUser) {
    def estate = Estate.get(pEstateId)
    if (estate == null || estate.approveFlag != '0') {
      return false
    }
    if (pFlag == '1') {
      def setting = Setting.get(1)
      def user = estate.createUser
      user.availableMoney += setting.estateMoneyPresented
      user.availablePoint += setting.estatePointPresented
      user.availableCoupon += setting.estateCouponPresented
      if (!user.save()) {
        user.errors.each {
          println it
        }
      }
      def bid = new Bid()
      bid.estate = estate
      bid.type = "20"
      bid.user = user
      bid.money = 0
      bid.payment = "40"
      bid.dayCost = 0
      if (!bid.save()) {
        bid.errors.each {
          println it
        }
      }
      estate.curMthVipBid = bid
    }
    estate.approveFlag = pFlag
    estate.approveUser = pApproveUser
    estate.dateApproved = new Date()
    if (pFlag == '2') {
      estate.showFlag = '0'
    }
    if (!estate.save()) {
      estate.errors.each {
        println it
      }
    }
    return true
  }
}
